﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.Threading;

public partial class JobManage_ClientMateReceiptList :BasePage
{
    DataBase db = new DataBase();
    IJobHandler jobManage = new JobHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    IRolePurviewHandler userManage = new RolePurviewHandler();
    ISystemHandler systemManage = new SystemHandler();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!(strPermission.Contains("1077")))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
            }

            ViewState["OrderBy"] = "ConfirmDate";
            ViewState["Accending"] = "asc";
            FillDDl();
            dataBind();
        }
    }

    #region FillDDl
    private void FillDDl()
    {
        //绑定托运人
        DataTable dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.TYR.ToString("d")));
        ddlShipper.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlShipper.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlShipper.DataTextField = "HKShortName";
        }
        else
        {
            ddlShipper.DataTextField = "CNShortName";
        }
        ddlShipper.DataValueField = "PKID";
        ddlShipper.DataBind();
        ddlShipper.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //工厂
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.GC.ToString("d")));
        //ddlVendor.DataSource = dt;
        //if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        //{
        //    ddlVendor.DataTextField = "ENGShortName";
        //}
        ddlVendor.Items.Add(new ListItem(Resources.Messages.PleaseSelect, "0"));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ListItem item = new ListItem();
            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                // ddlVendor.DataTextField = "HKShortName";
                item.Text = dt.Rows[i]["ENGShortName"].ToString() + "/" + dt.Rows[i]["HKShortName"].ToString();
            }
            else
            {
                item.Text = dt.Rows[i]["ENGShortName"].ToString() + "/" + dt.Rows[i]["CNShortName"].ToString();
                //ddlVendor.DataTextField = "CNShortName";
            }
            item.Value = dt.Rows[i]["PKID"].ToString();
            // ddlVendor.DataValueField = "PKID";
            ddlVendor.Items.Add(item);
        }
        // ddlVendor.DataBind();
        // ddlVendor.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //仓库
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.CK.ToString("d")));
        ddlWhouse.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlWhouse.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlWhouse.DataTextField = "HKShortName";
        }
        else
        {
            ddlWhouse.DataTextField = "CNShortName";
        }
        ddlWhouse.DataValueField = "PKID";
        ddlWhouse.DataBind();
        ddlWhouse.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));
    }
    #endregion

    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";
        UsersQuery userQuery = userManage.GetUsers(int.Parse(Session["UserID"].ToString()));
        if (userQuery != null)
        {

            list.Add(new SqlParameter("@Contractor", userQuery.ClientID.ToString()));
            sqlstr += " and Contractor=@Contractor ";

            if (ViewState["Shipper"] != null)
            {
                list.Add(new SqlParameter("@ShipperID", ViewState["ShipperID"].ToString()));
                sqlstr += " and ShipperID=@ShipperID";
            }
            if (ViewState["Whse"] != null)
            {
                list.Add(new SqlParameter("@WhseID", ViewState["Whse"].ToString()));
                sqlstr += " and WhouseID=@WhseID";
            }

            if (ViewState["Vendor"] != null)
            {
                list.Add(new SqlParameter("@VendorID", ViewState["Vendor"].ToString()));
                sqlstr += " and VendorID=@VendorID";

            }

            if (ViewState["DateFrom"] != null && ViewState["DateTo"] != null)
            {
                list.Add(new SqlParameter("@DateFrom", ViewState["DateFrom"].ToString().ToString()));
                list.Add(new SqlParameter("@DateTo", ViewState["DateTo"].ToString()));
                sqlstr += " and JobDate between @DateFrom and @DateTo ";
            }
            else if (ViewState["DateFrom"] != null && ViewState["DateTo"] == null)
            {
                list.Add(new SqlParameter("@DateFrom", ViewState["DateFrom"].ToString().ToString()));
                sqlstr += " and JobDate >= @DateFrom ";
            }
            else if (ViewState["DateFrom"] == null && ViewState["DateTo"] != null)
            {
                list.Add(new SqlParameter("@DateTo", ViewState["DateTo"].ToString().ToString()));
                sqlstr += " and JobDate <= @DateTo ";
            }

            if (ViewState["DeliveryDateFrom"] != null && ViewState["DeliveryDateTo"] != null)
            {
                list.Add(new SqlParameter("@DeliveryDateFrom", ViewState["DeliveryDateFrom"].ToString().ToString()));
                list.Add(new SqlParameter("@DeliveryDateTo", ViewState["DeliveryDateTo"].ToString()));
                sqlstr += " and DeliveryDate between @DeliveryDateFrom and @DeliveryDateTo ";
            }
            else if (ViewState["DeliveryDateFrom"] != null && ViewState["DeliveryDateTo"] == null)
            {
                list.Add(new SqlParameter("@DeliveryDateFrom", ViewState["DeliveryDateFrom"].ToString().ToString()));
                sqlstr += " and DeliveryDate >= @DeliveryDateFrom ";
            }
            else if (ViewState["DeliveryDateFrom"] == null && ViewState["DeliveryDateTo"] != null)
            {
                list.Add(new SqlParameter("@DeliveryDateTo", ViewState["DeliveryDateTo"].ToString().ToString()));
                sqlstr += " and DeliveryDate <= @DeliveryDateTo ";
            }

            if (ViewState["MateReceiptDateFrom"] != null && ViewState["MateReceiptDateTo"] != null)
            {
                list.Add(new SqlParameter("@MateReceiptDateFrom", ViewState["MateReceiptDateFrom"].ToString().ToString()));
                list.Add(new SqlParameter("@MateReceiptDateTo", ViewState["MateReceiptDateTo"].ToString()));
                sqlstr += " and MateReceiptDate between @MateReceiptDateFrom and @MateReceiptDateTo ";
            }
            else if (ViewState["MateReceiptDateFrom"] != null && ViewState["MateReceiptDateTo"] == null)
            {
                list.Add(new SqlParameter("@MateReceiptDateFrom", ViewState["MateReceiptDateFrom"].ToString().ToString()));
                sqlstr += " and MateReceiptDate >= @MateReceiptDateFrom ";
            }
            else if (ViewState["MateReceiptDateFrom"] == null && ViewState["MateReceiptDateTo"] != null)
            {
                list.Add(new SqlParameter("@MateReceiptDateTo", ViewState["MateReceiptDateTo"].ToString().ToString()));
                sqlstr += " and MateReceiptDate <= @MateReceiptDateTo ";
            }



            if (ViewState["SONO"] != null)
            {
                list.Add(new SqlParameter("@SONO", txtSONO.Text.Trim()));
                sqlstr += " and SONO like @SONO ";
            }

            list.Add(new SqlParameter("@Status", Enums.ShippingOrderStatus.PRINT.ToString("d")));
            list.Add(new SqlParameter("@Status1", Enums.ShippingOrderStatus.MATECONFIRM.ToString("d")));
            list.Add(new SqlParameter("@Status2", Enums.ShippingOrderStatus.CONFIM.ToString("d")));
            sqlstr += " and (Status = @Status or Status = @Status1 or Status=@Status2)";

            parms = list.ToArray();
        }

    }

    private void dataBind()
    {
        if (Session["UserID"] != null)
        {
            string sqlStr = @"SELECT BN.*,WhouseID,SONO,JobDate,GrossWT,VOL,ShipperID,BNDtl.Remark,BNDtl.DeliveryDate,
                        
                           (select CNShortName from Sy_Client as SC where SC.PKID=BN.Contractor) as ContractorCNShortName ,
                        (select ENGShortName from Sy_Client as SC where SC.PKID=BN.Contractor) as ContractorENGShortName,
                        (select HKShortName from Sy_Client as SC where SC.PKID=BN.Contractor) as ContractorHKShortName,
                             (SELECT [values] FROM(
            SELECT [values] = STUFF(REPLACE(REPLACE((
                SELECT DISTINCT LicenseNO FROM BN_SendTruck st INNER JOIN
                    BN_SendTruckDtl stDtl ON st.PKID = SendTruckID INNER JOIN
                    BN_Truck truck ON stDtl.TruckID = truck.PKID
                WHERE st.OrderID = BN.PKID AND
                    st.Contractor = BN.Contractor
                FOR XML AUTO
            ), '<truck LicenseNO=" + "\"" + "', ', '),'" + "\"" + @"/>', ''),1,1,'')
        )N) as LicenseNO,
        
                (SELECT [values] FROM(
            SELECT [values] = STUFF(REPLACE(REPLACE((
                SELECT DISTINCT Model FROM BN_SendTruck st INNER JOIN
                    BN_SendTruckDtl stDtl ON st.PKID = SendTruckID INNER JOIN
                    Sy_ContainerModel model ON stDtl.TypeID = model.PKID
                WHERE st.OrderID = BN.PKID AND
                    st.Contractor = BN.Contractor
                FOR XML AUTO
            ), '<model Model=" + "\"" + "', ', '),'" + "\"" + @"/>', ''),1,1,'')
        )N) as Model

                        FROM BN_ShippingOrder as BN,BN_ShippingOrderDtl as BNDtl where BN.PKID=BNDtl.OrderID ";
            SqlParameter[] parms = null;
            string clause = string.Empty;
            ProcessParms(ref clause, ref parms);
            sqlStr += clause;

            DataTable dt = jobManage.GetShippingOrder(sqlStr, parms);
            DataView view = dt.DefaultView;
            view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"] +",PKID desc";
            gvJobList.DataSource = view;
            gvJobList.DataBind();
            if (dt != null && dt.Rows.Count > 0)
            {
                lblTotal.Text = dt.Rows.Count.ToString();
            }
            else
            {
                lblTotal.Text = "0";
            }
        }
    }

    protected void gvJobList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvJobList.PageIndex = e.NewPageIndex;
        dataBind();

    }
    protected void gvJobList_RowCommand(object sender, GridViewCommandEventArgs e)
    {

    }
    protected void gvJobList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (ddlShipper.SelectedValue != "0")
        {

            ViewState["Shipper"] = ddlShipper.SelectedValue;
        }
        else
        {
            ViewState["Shipper"] = null;
        }

        if (ddlVendor.SelectedValue != "0")
        {

            ViewState["Vendor"] = ddlVendor.SelectedValue;
        }
        else
        {
            ViewState["Vendor"] = null;
        }
        if (ddlWhouse.SelectedValue != "0")
        {

            ViewState["Whse"] = ddlWhouse.SelectedValue;
        }
        else
        {
            ViewState["Whse"] = null;
        }

        if (txtDateFrom.Text != string.Empty && txtDateTo.Text != string.Empty)
        {
            ViewState["DateFrom"] = txtDateFrom.Text.Trim() + " 00:00:00";

            ViewState["DateTo"] = txtDateTo.Text.Trim() + " 23:59:59";
        }
        else if (txtDateFrom.Text != string.Empty && txtDateTo.Text == string.Empty)
        {
            ViewState["DateFrom"] = txtDateFrom.Text.Trim() + " 23:59:59";

            ViewState["DateTo"] = null;
        }
        else if (txtDateFrom.Text == string.Empty && txtDateTo.Text != string.Empty)
        {

            ViewState["DateFrom"] = null;
            ViewState["DateTo"] = txtDateTo.Text.Trim() + " 23:59:59";
        }
        else
        {
            ViewState["DateFrom"] = null;
            ViewState["DateTo"] = null;
        }


        if (txtDeliveryDateFrom.Text != string.Empty && txtDeliveryDateTo.Text != string.Empty)
        {
            ViewState["DeliveryDateFrom"] = txtDeliveryDateFrom.Text.Trim() + " 00:00:00";

            ViewState["DeliveryDateTo"] = txtDeliveryDateTo.Text.Trim() + " 23:59:59";
        }
        else if (txtDeliveryDateFrom.Text != string.Empty && txtDeliveryDateTo.Text == string.Empty)
        {
            ViewState["DeliveryDateFrom"] = txtDeliveryDateFrom.Text.Trim() + " 23:59:59";

            ViewState["DeliveryDateTo"] = null;
        }
        else if (txtDeliveryDateFrom.Text == string.Empty && txtDeliveryDateTo.Text != string.Empty)
        {

            ViewState["DeliveryDateFrom"] = null;
            ViewState["DeliveryDateTo"] = txtDeliveryDateTo.Text.Trim() + " 23:59:59";
        }
        else
        {
            ViewState["DeliveryDateFrom"] = null;
            ViewState["DeliveryDateTo"] = null;
        }

        if (txtMateReceiptDateFrom.Text != string.Empty && txtMateReceiptDateTo.Text != string.Empty)
        {
            ViewState["MateReceiptDateFrom"] = txtMateReceiptDateFrom.Text.Trim() + " 00:00:00";

            ViewState["MateReceiptDateTo"] = txtMateReceiptDateTo.Text.Trim() + " 23:59:59";
        }
        else if (txtMateReceiptDateFrom.Text != string.Empty && txtMateReceiptDateTo.Text == string.Empty)
        {
            ViewState["MateReceiptDateFrom"] = txtMateReceiptDateFrom.Text.Trim() + " 23:59:59";

            ViewState["MateReceiptDateTo"] = null;
        }
        else if (txtMateReceiptDateFrom.Text == string.Empty && txtMateReceiptDateTo.Text != string.Empty)
        {

            ViewState["MateReceiptDateFrom"] = null;
            ViewState["MateReceiptDateTo"] = txtMateReceiptDateTo.Text.Trim() + " 23:59:59";
        }
        else
        {
            ViewState["MateReceiptDateFrom"] = null;
            ViewState["MateReceiptDateTo"] = null;
        }


        if (txtSONO.Text != string.Empty)
        {
            ViewState["SONO"] = txtSONO.Text.Trim();
        }
        else
        {
            ViewState["SONO"] = null;
        }

        dataBind();
    }


    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvJobList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvJobList.PageCount)
            {
                this.gvJobList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
                Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);
                return;
            }
        }
        catch
        {
            // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
            Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);

        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvJobList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }

    public string GetClient(object id)
    {
        return systemManage.GetClient(id);
    }

    public string GetUserName(object userID)
    {
        return systemManage.GetUserName(userID);
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            string[] pkid = Request["chkSelected"].Split(new char[] { ',' });

            SqlParameter[] parms = null;
            List<SqlParameter> list = new List<SqlParameter>();
            string sqlStr = string.Empty;


            if (txtMateReceiptDate.Text != string.Empty || txtDeliveryDate.Text != string.Empty)
            {
                if (txtMateReceiptDate.Text != string.Empty && txtDeliveryDate.Text != string.Empty)
                {
                    list.Add(new SqlParameter("@IsConfirmMateReceipt", "1"));//已确认
                    list.Add(new SqlParameter("@MateReceiptDate", txtMateReceiptDate.Text.Trim()));
                    list.Add(new SqlParameter("@MateReceiptConfirmUser", Session["UserID"].ToString()));
                    list.Add(new SqlParameter("@BookingNoteDtlStatus", Enums.BookingNoteDtlStatus.MATECONFIRM.ToString("d")));
                    list.Add(new SqlParameter("@SOStatus", Enums.ShippingOrderStatus.MATECONFIRM.ToString("d")));

                    list.Add(new SqlParameter("@DeliveryDate", txtDeliveryDate.Text.Trim()));

                    for (int i = 0; i < pkid.Length; i++)
                    {
                        list.Add(new SqlParameter("@OrderID" + i.ToString(), pkid[i]));

                        sqlStr += "update BN_ShippingOrder set Status=@SOStatus,IsConfirmMateReceipt=@IsConfirmMateReceipt,MateReceiptDate=@MateReceiptDate,MateReceiptConfirmUser=@MateReceiptConfirmUser where PKID=@OrderID" + i.ToString() + "; ";
                        sqlStr += "update BN_BookingNoteDtl set Status=@BookingNoteDtlStatus,ReceiptDate=@MateReceiptDate,ReceiptUser=@MateReceiptConfirmUser,DeliveryDate=@DeliveryDate where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID" + i.ToString() + "));";
                        sqlStr += "update BN_BookingDtl set DeliveryDate=@DeliveryDate where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID" + i.ToString() + ");";
                        sqlStr += "update BN_ShippingOrderDtl set DeliveryDate=@DeliveryDate where OrderID=@OrderID" + i.ToString() + ";";
                    }
                }
                else if (txtMateReceiptDate.Text != string.Empty && txtDeliveryDate.Text == string.Empty)
                {
                    list.Add(new SqlParameter("@IsConfirmMateReceipt", "1"));//已确认
                    list.Add(new SqlParameter("@MateReceiptDate", txtMateReceiptDate.Text.Trim()));
                    list.Add(new SqlParameter("@MateReceiptConfirmUser", Session["UserID"].ToString()));
                    list.Add(new SqlParameter("@BookingNoteDtlStatus", Enums.BookingNoteDtlStatus.MATECONFIRM.ToString("d")));
                    list.Add(new SqlParameter("@SOStatus", Enums.ShippingOrderStatus.MATECONFIRM.ToString("d")));

                    for (int i = 0; i < pkid.Length; i++)
                    {
                        list.Add(new SqlParameter("@OrderID" + i.ToString(), pkid[i]));

                        sqlStr += "update BN_ShippingOrder set Status=@SOStatus,IsConfirmMateReceipt=@IsConfirmMateReceipt,MateReceiptDate=@MateReceiptDate,MateReceiptConfirmUser=@MateReceiptConfirmUser where PKID=@OrderID" + i.ToString() + "; ";
                        sqlStr += "update BN_BookingNoteDtl set Status=@BookingNoteDtlStatus,ReceiptDate=@MateReceiptDate,ReceiptUser=@MateReceiptConfirmUser where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID" + i.ToString() + "));";
                    }
                }
                else if (txtMateReceiptDate.Text == string.Empty && txtDeliveryDate.Text != string.Empty)
                {
                    list.Add(new SqlParameter("@DeliveryDate", txtDeliveryDate.Text.Trim()));

                    for (int i = 0; i < pkid.Length; i++)
                    {
                        list.Add(new SqlParameter("@OrderID" + i.ToString(), pkid[i]));

                        sqlStr += "update BN_BookingNoteDtl set DeliveryDate=@DeliveryDate where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID" + i.ToString() + "));";
                        sqlStr += "update BN_BookingDtl set DeliveryDate=@DeliveryDate where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID" + i.ToString() + ");";
                        sqlStr += "update BN_ShippingOrderDtl set DeliveryDate=@DeliveryDate where OrderID=@OrderID" + i.ToString() + ";";

                    }
                }

                parms = list.ToArray();
                if (db.ExecSqlTransaction(sqlStr, parms))
                {
                    if (txtMateReceiptDate.Text != string.Empty)
                    {
                        Jscript.AlertInAjax(Resources.Messages.MateReceiptConfirmSuccess, UpdatePanel1);
                    }
                    else
                    {
                        Jscript.AlertInAjax(Resources.Messages.DeliveryDateSuccess, UpdatePanel1);
                    }
                }
                else
                {
                    if (txtMateReceiptDate.Text != string.Empty)
                    {
                        Jscript.AlertInAjax(Resources.Messages.MateReceiptConfirmFailed, UpdatePanel1);
                    }
                    else
                    {
                        Jscript.AlertInAjax(Resources.Messages.MateReceiptConfirmFailed, UpdatePanel1);
                    }
                }
                dataBind();

            }
        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.PleaseSelect, UpdatePanel1);
            return;
        }

    }

}
